package org.yhhhhhhh.ai_jianli.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.yhhhhhhh.ai_jianli.model.User;
import org.yhhhhhhh.ai_jianli.service.JwtService;
import org.yhhhhhhh.ai_jianli.service.RegistrationService;
import org.yhhhhhhh.ai_jianli.service.UserService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AuthController {

    @Autowired
    private RegistrationService registrationService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private AuthenticationManager authenticationManager;

    // 登录页面
    @GetMapping("/login")
    public String showLoginPage(@RequestParam(value = "error", required = false) String error,
                                @RequestParam(value = "logout", required = false) String logout,
                                Model model) {
        if (error != null) {
            model.addAttribute("error", "用户名或密码错误");
        }

        if (logout != null) {
            model.addAttribute("message", "您已成功注销");
        }

        return "login";
    }

    // 注册页面
    @GetMapping("/register")
    public String showRegistrationPage(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    // 处理注册请求 - 修复密码传递问题
    @PostMapping("/register")
    public String registerUser(@ModelAttribute("user") User user,
                               @RequestParam("password") String password, // 直接获取密码参数
                               @RequestParam("confirmPassword") String confirmPassword,
                               RedirectAttributes redirectAttributes) {
        try {
            // 验证密码是否匹配
            if (!password.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("error", "两次输入的密码不匹配");
                return "redirect:/register";
            }

            // 注册用户 - 使用直接获取的密码
            registrationService.registerUser(user.getUsername(), user.getEmail(), password);

            redirectAttributes.addFlashAttribute("message", "注册成功，请登录");
            return "redirect:/login";
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/register";
        }
    }

    // 聊天页面（需要认证）
    @GetMapping("/chat")
    public String showChatPage(Model model) {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            model.addAttribute("currentUser", authentication.getName());
            model.addAttribute("isAdmin", authentication.getAuthorities().stream()
                    .anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN")));
        }
        return "chat";
    }



    // 结果页面（需要认证）
    @GetMapping("/result")
    public String showResultPage() {
        return "result";
    }
    @Autowired
    private UserService userService;

    @GetMapping
    public String showManagerPage(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        model.addAttribute("newUser", new User());
        return "manager";
    }

    @PostMapping("/add")
    public String addUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/manager";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return "redirect:/manager";
    }

    @PostMapping("/update/{id}")
    public String updateUser(@PathVariable Long id, @ModelAttribute User user) {
        user.setId(id);
        userService.save(user);
        return "redirect:/manager";
    }

    @GetMapping("/search")
    public String searchUsers(@RequestParam String keyword, Model model) {
        List<User> users = userService.searchUsers(keyword);
        model.addAttribute("users", users);
        model.addAttribute("newUser", new User());
        return "manager";
    }

    // ========== JWT API 端点 ==========

    /**
     * JWT登录接口
     * @param loginRequest 登录请求，包含用户名和密码
     * @return JWT token和用户信息
     */
    @PostMapping("/api/auth/login")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String username = loginRequest.get("username");
            String password = loginRequest.get("password");

            // 验证用户凭据
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );

            // 获取用户详情
            User user = (User) userService.loadUserByUsername(username);

            // 生成JWT token
            String token = jwtService.generateToken(user);

            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("token", token);
            response.put("user", Map.of(
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "email", user.getEmail(),
                    "roles", user.getRoles()
            ));

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户名或密码错误");
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * JWT注册接口
     * @param registerRequest 注册请求，包含用户名、邮箱和密码
     * @return 注册结果
     */
    @PostMapping("/api/auth/register")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> registerRequest) {
        try {
            String username = registerRequest.get("username");
            String email = registerRequest.get("email");
            String password = registerRequest.get("password");
            String confirmPassword = registerRequest.get("confirmPassword");

            // 验证密码是否匹配
            if (!password.equals(confirmPassword)) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "两次输入的密码不匹配");
                return ResponseEntity.badRequest().body(response);
            }

            // 注册用户
            registrationService.registerUser(username, email, password);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "注册成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 验证JWT token
     * @param token JWT token
     * @return 验证结果和用户信息
     */
    @PostMapping("/api/auth/validate")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> validateToken(@RequestBody Map<String, String> tokenRequest) {
        try {
            String token = tokenRequest.get("token");
            
            if (token == null || token.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            User user = jwtService.validateTokenAndGetUser(token);
            
            if (user != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "Token有效");
                response.put("user", Map.of(
                        "id", user.getId(),
                        "username", user.getUsername(),
                        "email", user.getEmail(),
                        "roles", user.getRoles()
                ));
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token无效或已过期");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Token验证失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 刷新JWT token
     * @param tokenRequest 包含旧token的请求
     * @return 新的JWT token
     */
    @PostMapping("/api/auth/refresh")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> refreshToken(@RequestBody Map<String, String> tokenRequest) {
        try {
            String token = tokenRequest.get("token");
            
            if (token == null || token.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证旧token
            User user = jwtService.validateTokenAndGetUser(token);
            
            if (user != null) {
                // 生成新token
                String newToken = jwtService.generateToken(user);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "Token刷新成功");
                response.put("token", newToken);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token无效，无法刷新");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Token刷新失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取当前用户信息（需要JWT认证）
     * @param authHeader Authorization请求头
     * @return 当前用户信息
     */
    @GetMapping("/api/auth/me")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getCurrentUser(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "缺少Authorization请求头");
                return ResponseEntity.badRequest().body(response);
            }

            String token = jwtService.extractTokenFromHeader(authHeader);
            User user = jwtService.validateTokenAndGetUser(token);
            
            if (user != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("user", Map.of(
                        "id", user.getId(),
                        "username", user.getUsername(),
                        "email", user.getEmail(),
                        "roles", user.getRoles()
                ));
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token无效或已过期");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取用户信息失败");
            return ResponseEntity.badRequest().body(response);
        }
    }
}
